<template>
  <div>
    <el-dialog :title="title" :visible="visible" width="40%" @close="resetForm">
      <el-form ref="elForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="奖品名称：" prop="couponName">
          <el-input v-model="formData.couponName" placeholder="请输入奖品名称（1-10个字）" />
        </el-form-item>

        <el-form-item label="积分值：" prop="couponIntegral">
          <el-input
            v-model.number="formData.couponIntegral"
            placeholder="请输入积分值（1-100000，仅限正整数）"
          />
        </el-form-item>

        <el-form-item label="中奖概率：" prop="acquireRatio">
          <el-row>
            <el-col :span="22">
              <el-input
                v-model.number="formData.acquireRatio"
                placeholder="请输入中奖概率（1-99，仅限正整数）"
              />
            </el-col>
            <el-col :span="2">
              <span class="ml-10">%</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button @click="resetForm"> 取消 </el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { useGenerateUUID } from '@/hooks'
export default {
  name: 'AddCouponPopup',
  props: {
    rowId: {
      required: true,
      default: ''
    },
    rowData: Object,
    dialogVisible: {
      type: Boolean,
      default: false
    },
    countTotal: Number,
    type: String,
    value: Array
  },
  data() {
    return {
      formData: {
        couponName: '',
        acquireRatio: '',
        couponIntegral: '',
        couponsItemTotal: ''
      },
      rules: {
        couponName: [
          {
            required: true,
            message: '请输入奖品名称'
          },
          {
            min: 1,
            max: 10,
            message: '请输入1-10个字'
          }
        ],
        acquireRatio: [
          {
            required: true,
            message: '请输入中奖概率'
          },
          {
            pattern: /^[1-9]\d{0,1}$/,
            message: '请输入1-99的正整数'
          }
        ],
        couponIntegral: [
          {
            required: true,
            message: '请输入积分值'
          },
          {
            pattern: /^([1-9][0-9]{0,4}|100000)$/,
            message: '请输入1-100000的正整数'
          }
        ]
      }
    }
  },
  computed: {
    title() {
      return this.rowId ? '编辑中奖选项' : '添加中奖选项'
    },
    visible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val)
      }
    },
    giftCouponConfigBackPos: {
      get() {
        return this.value
      },
      set(value) {
        this.$emit('input', value)
      }
    }
  },
  watch: {
    // 存在总数量，计算数量
    countTotal(value) {
      if (value) {
        this.giftCouponConfigBackPos = this.giftCouponConfigBackPos.map(item => {
          return {
            ...item,
            couponsItemTotal: parseInt(this.countTotal * (item.acquireRatio / 100))
          }
        })
      }
    }
  },
  created() {
    for (const key in this.formData) {
      if (this.rowData) {
        this.formData[key] = this.rowData[key]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        if (this.rowId) {
          this.giftCouponConfigBackPos = this.giftCouponConfigBackPos.map(item => {
            let id = item.id || item.uuid
            if (id === this.rowId) {
              return {
                ...item,
                ...this.formData,
                couponsItemTotal: parseInt(this.countTotal * (this.formData.acquireRatio / 100))
              }
            }
            return item
          })
        } else {
          this.giftCouponConfigBackPos = [
            { uuid: useGenerateUUID(), ...this.formData },
            ...this.giftCouponConfigBackPos
          ].map(item => {
            return {
              ...item,
              couponsItemTotal: parseInt(this.countTotal * (item.acquireRatio / 100))
            }
          })
        }

        // 计算总概率不能超过100%
        if (this.giftCouponConfigBackPos.length) {
          let couponCount = this.giftCouponConfigBackPos?.reduce((prev, next) => {
            return Number(prev) + Number(next.acquireRatio)
          }, [])

          if (couponCount > 100) {
            // 去掉超出概率的数据
            this.giftCouponConfigBackPos.splice(0, 1)
            return this.$message.error('目前中奖概率达到100%，无法添加！')
          }
        }
        this.$emit('update')
        this.visible = false
      })
    },
    resetForm() {
      this.visible = false
      this.$emit('update')
      this.$refs['elForm'].resetFields()
    }
  }
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
